using NHibernate;
using NHibernate.Cfg;
using NHibernate.Tool.hbm2ddl;

using Tickets.Model;
using Tickets.Model.Repositories;

namespace Tickets.Infrastructure
{
	public class SchemaUtil : ISchemaUtil
	{
		private IProjectRepository _projectRepository;
		private ISessionFactory _sessionFactory;
		private Configuration _configuration;

		// Estos parametros son injectados en runtime por el framework de IoC (Windsor)
		public SchemaUtil( IProjectRepository projectRepository, ISessionFactory sessionFactory, Configuration configuration )
		{
			_projectRepository = projectRepository;
			_sessionFactory = sessionFactory;
			_configuration = configuration;
		}

		public void RebuildSchema()
		{
			new SchemaExport( _configuration ).Create( false, true );
		}

		public virtual void LoadTestData()
		{
			Project project1 = new Project("TST", "Proyecto de prueba numero 1");
			project1.AddTicket("TST-1", "Primer ticket de projecto 1");
			project1.AddTicket("TST-2", "Segundo ticket de projecto 1");
			_projectRepository.Add(project1);

			Project project2 = new Project("PRB", "Proyecto de prueba numero 2");
			project2.AddTicket("PRB-3", "Primer ticket de projecto 2");
			project2.AddTicket("PRB-4", "Segundo ticket de projecto 2");
			project2.AddTicket("PRB-5", "Segundo ticket de projecto 2");
			_projectRepository.Add(project2);

			Project project3 = new Project("TKT", "Proyecto de prueba numero 3");
			_projectRepository.Add(project3);
		}

		public void DropSchema()
		{
			new SchemaExport( _configuration ).Drop( false, true );
		}

		public ISession CreateSession()
		{
			return _sessionFactory.OpenSession();
		}
	}
}